package com.yskj.tms.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yskj.tms.common.UsersById;
import com.yskj.tms.entity.ShipAndTransport;
import com.yskj.tms.entity.ShipInfo;
import com.yskj.tms.entity.TransportPlan;
import com.yskj.tms.entity.UserInfo;
import com.yskj.tms.service.TransportService;
import com.yskj.tms.util.FiledUtil;
import com.yskj.tms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

/**
 * Created by Administrator on 2018/4/26.
 */
@Controller
public class TransportController {

    @Autowired
    private TransportService transportService;

    private UsersById users = new UsersById();

    @RequestMapping("/searchTransport.do")
    public ModelAndView toSearchTransport(HttpServletRequest request, @RequestParam(value="ordernumber",required=false) String ordernumber, @RequestParam(value="goodsownername",required=false) String goodsownername
            , @RequestParam(value="start",required=false) String startdate, @RequestParam(value="end",required=false) String enddate,@RequestParam(value = "pn",defaultValue="1") int pageNum) throws  Exception{
//       HttpSession session = request.getSession();
//       int userid = (int) session.getAttribute("userid");
        Map map = new HashMap();
        map.put("userid",users.getUserid(request));
        map.put("ordernumber",ordernumber);
        map.put("goodsownername",goodsownername);
        map.put("stats",0);
        if (!StringUtil.isEmpty(startdate) && !StringUtil.isEmpty(enddate) ){
            Date starttime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startdate +" 00:00:00");
            Date endtime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(enddate+" 23:59:59");
            map.put("startdate",new Timestamp(starttime.getTime()));
            map.put("enddate",new Timestamp(endtime.getTime()));
        }else {
            map.put("startdate",startdate);
            map.put("enddate",enddate);
        }
        PageHelper.startPage(pageNum,5);
        List<TransportPlan>  transportPlanList= transportService.selectByUseridToTransportQuery(map);
        PageInfo pageInfo = new PageInfo(transportPlanList);
        ModelAndView mav = new ModelAndView("/transport/transport");
        if (transportPlanList != null){
            mav.addObject("pageInfo",pageInfo);
            mav.addObject("list",transportPlanList);
        }
        return mav;
    }

    @RequestMapping("/selectShipinfosByTid.do")
    @ResponseBody
    public String selectShipInfosByTid(@RequestParam(value = "tid")int tid) throws Exception{
        TransportPlan transportPlan =  transportService.selectShipInfosByTidQuery(tid);
        List<ShipInfo> shipInfoList = transportPlan.getShipInfoList();
        for(int i=0;i<shipInfoList.size();i++){
            String cname = FiledUtil.getAdd(shipInfoList.get(i).getDeviceInfo().getLongitude(), shipInfoList.get(i).getDeviceInfo().getLatitude());
            shipInfoList.get(i).getDeviceInfo().setCname(cname);
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("transport",transportPlan);
        return new ObjectMapper().writeValueAsString(map);
    }

    @RequestMapping("/selectShipAndTransport.do")
    @ResponseBody
    public String selectShipAndTransport(@RequestParam(value = "tid")int tid,@RequestParam(value = "shipid")int shipid)throws Exception{
        ShipAndTransport shipAndTransport = transportService.selectShipAndTransportByQuery(tid,shipid);
        return new ObjectMapper().writeValueAsString(shipAndTransport);
    }

    @RequestMapping("/updateShipAndTransport.do")
    public void updateShipAndTransport(HttpServletRequest request)throws Exception{
        Map map = new HashMap();
        if (!StringUtil.isEmpty(request.getParameter("shipid"))){
            map.put("shipid",request.getParameter("shipid"));
        }
        if (!StringUtil.isEmpty(request.getParameter("tid"))){
            map.put("tid",request.getParameter("tid"));
        }
        if (!StringUtil.isEmpty(request.getParameter("origporttime"))){
            map.put("origporttime",request.getParameter("origporttime"));
        }
        if (!StringUtil.isEmpty(request.getParameter("arriveporttime"))){
            map.put("arriveporttime",request.getParameter("arriveporttime"));
        }
        if (!StringUtil.isEmpty(request.getParameter("unloadtime"))){
            map.put("unloadtime",request.getParameter("unloadtime"));
        }
        if (!StringUtil.isEmpty(request.getParameter("loadton"))){
            map.put("loadton",request.getParameter("loadton"));
        }
        if (!StringUtil.isEmpty(request.getParameter("realton"))){
            map.put("realton",request.getParameter("realton"));
        }
        if (!StringUtil.isEmpty(request.getParameter("fulltime"))){
            map.put("fulltime",request.getParameter("fulltime"));
        }
        if (!StringUtil.isEmpty(request.getParameter("startloadingtime"))){
            map.put("startloadingtime",request.getParameter("startloadingtime"));
        }
        if (!StringUtil.isEmpty(request.getParameter("startunloadingtime"))){
            map.put("startunloadingtime",request.getParameter("startunloadingtime"));
        }
        if (!StringUtil.isEmpty(request.getParameter("planton"))){
            map.put("planton",request.getParameter("planton"));
        }
        transportService.updateShipAndTransportByQuery(map);
    }

    @RequestMapping("exportShipInfoAndTransportListExcel.do")
    public void exportShipInfoAndTransportListExcel( HttpServletRequest request, HttpServletResponse response, @RequestParam(value="ordernumber",required=false) String ordernumber, @RequestParam(value="goodsownername",required=false) String goodsownername
            , @RequestParam(value="start",required=false) String startdate, @RequestParam(value="end",required=false) String enddate) throws Exception{
//        HttpSession session =request.getSession();
//        Object userids = session.getAttribute("userid");
//        int userid = 0;
//        if (userids !=null){
//            userid =(int)userids;
//        }
        Map map = new HashMap();
        map.put("userid",users.getUserid(request));
        map.put("ordernumber",ordernumber);
        map.put("goodsownername",goodsownername);
        map.put("startdate",startdate);
        map.put("enddate",enddate);
        map.put("stats",0);
        try
        {
            List<Map<String,Object>> transportPlanList= transportService.exportShipInfoAndTransportList(map);
            HSSFCell cell1;
            String sheetName = "TMS";
            String[] colName = { "运单编号", "计划创建日期", "货主", "货主联系方式", "货物类型", "船名","船主姓名","船主电话","运输状态","计划总吨位","发货地/发货港口","抵达发货地时间","开始装货时间","装货完成时间","受载吨位","当前动态","目的地/卸货港口","抵达目的地时间","开始卸货时间","卸货完成时间","实收吨位","航次周期(天)","调度员","备注"};
            int i = 0; int j = 0; int k = 0;
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(sheetName);
            HSSFRow row1 = sheet.createRow(0);

            for (k = 0; k < colName.length; ++k)
            {
                cell1 = row1.createCell(k);
                cell1.setCellValue(colName[k]);
            }
                for (i = 0; i < transportPlanList.size(); ++i)
                {
                    HSSFCell cell;
                    HSSFRow row = sheet.createRow(i + 1);
                    switch (i + 1) {
                        default:
                            for (j = 0; j < transportPlanList.get(i).size(); ++j)
                            {
                                cell = row.createCell(j);
                                switch (j)
                                {
                                    case 0:
                                        cell.setCellValue(transportPlanList.get(i).get("ordernumber").toString());
                                        break;
                                    case 1:
                                        String creationdate="";
                                        if (transportPlanList.get(i).get("creationdate")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("creationdate").toString())){

                                            creationdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm").format(transportPlanList.get(i).get("creationdate")).toString();
                                        }
                                        cell.setCellValue(creationdate);
                                        // cell.setCellValue(transportPlanList.get(i).get("creationdate").toString());
                                        break;
                                    case 2:
                                        String goodswnername="";
                                        if (transportPlanList.get(i).get("goodsownername")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("goodsownername").toString())){
                                            goodswnername =transportPlanList.get(i).get("goodsownername").toString();
                                        }
                                        cell.setCellValue(goodswnername);
                                        //cell.setCellValue(transportPlanList.get(i).get("goodsownername").toString());
                                        break;
                                    case 3:
                                        String goodsphone="";
                                        if (transportPlanList.get(i).get("goodsphone")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("goodsphone").toString())){
                                            goodsphone =transportPlanList.get(i).get("goodsphone").toString();
                                        }
                                        cell.setCellValue(goodsphone);
                                        //ell.setCellValue(transportPlanList.get(i).get("goodsphone").toString());
                                        break;
                                    case 4:
                                        String goodsname="";
                                        if (transportPlanList.get(i).get("goodsname")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("goodsname").toString())){
                                            goodsname =transportPlanList.get(i).get("goodsname").toString();
                                        }
                                        cell.setCellValue(goodsname);
                                        //cell.setCellValue(transportPlanList.get(i).get("goodsname").toString());
                                        break;
                                    case 5:
                                        String shipname="";
                                        if (transportPlanList.get(i).get("shipname")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("shipname").toString())){
                                            shipname =transportPlanList.get(i).get("shipname").toString();
                                        }
                                        cell.setCellValue(shipname);
                                        // cell.setCellValue(transportPlanList.get(i).get("shipname").toString());
                                        break;
                                    case 6:
                                        String shipownername="";
                                        if (transportPlanList.get(i).get("shipownername")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("shipownername").toString())){
                                            shipownername =transportPlanList.get(i).get("shipownername").toString();
                                        }
                                        cell.setCellValue(shipownername);
                                        // cell.setCellValue(transportPlanList.get(i).get("shipownername").toString());
                                        break;
                                    case 7:
                                        String shipownerphone="";
                                        if (transportPlanList.get(i).get("shipownerphone")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("shipownerphone").toString())){
                                            shipownerphone =transportPlanList.get(i).get("shipownerphone").toString();
                                        }
                                        cell.setCellValue(shipownerphone);
                                        //cell.setCellValue(transportPlanList.get(i).get("shipownerphone").toString());
                                        break;
                                    case 8:
                                        String isemtiy="";
                                        if (transportPlanList.get(i).get("isemtiy")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("isemtiy").toString())) {
                                            if (Integer.parseInt(transportPlanList.get(i).get("isemtiy").toString()) == 0) {
                                                isemtiy = "空载";
                                            } else {
                                                isemtiy = "满载";
                                            }
                                        }else{
                                            isemtiy="离线";
                                        }
                                        cell.setCellValue(isemtiy);
                                        break;
                                    case 9:
                                        String totaltonnage="";
                                        if (transportPlanList.get(i).get("totaltonnage")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("totaltonnage").toString())){
                                            totaltonnage =transportPlanList.get(i).get("totaltonnage").toString();
                                        }
                                        cell.setCellValue(totaltonnage);
                                        break;
                                    case 10:
                                        String originating="";
                                        if (transportPlanList.get(i).get("originating")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("originating").toString())){
                                            originating =transportPlanList.get(i).get("originating").toString();
                                        }
                                        cell.setCellValue(originating);
                                        break;
                                    case 11:
                                        String origporttime="";
                                        if (transportPlanList.get(i).get("origporttime")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("origporttime").toString())){
                                            origporttime =new SimpleDateFormat("yyyy-MM-dd HH:mm").format(transportPlanList.get(i).get("origporttime")).toString();
                                        }
                                        cell.setCellValue(origporttime);
//                                    cell.setCellValue(transportPlanList.get(i).get("origporttime").toString());
                                        break;
                                    case 12:
                                        String startloadingtime="";
                                        if (transportPlanList.get(i).get("startloadingtime")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("startloadingtime").toString())){
                                            startloadingtime =new SimpleDateFormat("yyyy-MM-dd HH:mm").format(transportPlanList.get(i).get("startloadingtime")).toString();
                                        }
                                        cell.setCellValue(startloadingtime);
                                        // cell.setCellValue(transportPlanList.get(i).get("fulltime").toString());
                                        break;
                                    case 13:
                                        String fulltime="";
                                        if (transportPlanList.get(i).get("fulltime")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("fulltime").toString())){
                                            fulltime =new SimpleDateFormat("yyyy-MM-dd HH:mm").format(transportPlanList.get(i).get("fulltime")).toString();
                                        }
                                        cell.setCellValue(fulltime);
                                        // cell.setCellValue(transportPlanList.get(i).get("fulltime").toString());
                                        break;
                                    case 14:
                                        ;String loadton="";
                                        if (transportPlanList.get(i).get("loadton")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("loadton").toString())){
                                            loadton =transportPlanList.get(i).get("loadton").toString();
                                        }
                                        cell.setCellValue(loadton);
                                        break;
                                    case 15:
                                        String cname="";
                                        if (transportPlanList.get(i).get("longitude")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("longitude").toString())&&transportPlanList.get(i).get("latitude")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("latitude").toString())){
                                            cname = FiledUtil.getAdd(transportPlanList.get(i).get("longitude").toString(),transportPlanList.get(i).get("latitude").toString());
                                        }
                                        cell.setCellValue(cname);
                                        break;
                                    case 16:
                                        String destination="";
                                        if (transportPlanList.get(i).get("destination")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("destination").toString())){
                                            destination =transportPlanList.get(i).get("destination").toString();
                                        }
                                        cell.setCellValue(destination);
                                        break;
                                    case 17:
                                        String arriveporttime="";
                                        if (transportPlanList.get(i).get("arriveporttime")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("arriveporttime").toString())){
                                            arriveporttime =new SimpleDateFormat("yyyy-MM-dd HH:mm").format(transportPlanList.get(i).get("arriveporttime")).toString();
                                        }
                                        cell.setCellValue(arriveporttime);
                                        //cell.setCellValue(transportPlanList.get(i).get("arriveporttime").toString());
                                        break;
                                    case 18:
                                        String startunloadingtime="";
                                        if (transportPlanList.get(i).get("startunloadingtime")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("startunloadingtime").toString())){
                                            startunloadingtime =new SimpleDateFormat("yyyy-MM-dd HH:mm").format(transportPlanList.get(i).get("startunloadingtime")).toString();
                                        }
                                        cell.setCellValue(startunloadingtime);
//                                    cell.setCellValue(transportPlanList.get(i).get("unloadtime").toString());
                                        break;
                                    case 19:
                                        String unloadtime="";
                                        if (transportPlanList.get(i).get("unloadtime")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("unloadtime").toString())){
                                            unloadtime =new SimpleDateFormat("yyyy-MM-dd HH:mm").format(transportPlanList.get(i).get("unloadtime")).toString();
                                        }
                                        cell.setCellValue(unloadtime);
//                                    cell.setCellValue(transportPlanList.get(i).get("unloadtime").toString());
                                        break;
                                    case 20:
                                        String realton="";
                                        if (transportPlanList.get(i).get("realton")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("realton").toString())){
                                            realton =transportPlanList.get(i).get("realton").toString();
                                        }
                                        cell.setCellValue(realton);
                                        break;
                                    case 21:
                                        long day= 0;
                                        if (transportPlanList.get(i).get("origporttime")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("origporttime").toString())&&transportPlanList.get(i).get("unloadtime")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("unloadtime").toString())){
                                            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd");
                                            Date ordate = simpleDateFormat.parse(transportPlanList.get(i).get("origporttime").toString());
                                            Date ardate = simpleDateFormat.parse(transportPlanList.get(i).get("unloadtime").toString());
                                            day=(ardate.getTime()-ordate.getTime())/(24*60*60*1000);
                                        }
                                        cell.setCellValue(day);
                                        break;
                                    case 22:
                                        String agentname="";
                                        if (transportPlanList.get(i).get("agentname")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("agentname").toString())){
                                            agentname =transportPlanList.get(i).get("agentname").toString();
                                        }
                                        cell.setCellValue(agentname);
                                        // cell.setCellValue(transportPlanList.get(i).get("remarkes").toString());
                                        break;
                                    case 23:
                                        String remarkes="";
                                        if (transportPlanList.get(i).get("remarkes")!=null&&!StringUtil.isEmpty(transportPlanList.get(i).get("remarkes").toString())){
                                            remarkes =transportPlanList.get(i).get("remarkes").toString();
                                        }
                                        cell.setCellValue(remarkes);
                                        // cell.setCellValue(transportPlanList.get(i).get("agentname").toString());
                                        break;
                                };
                            };
                            break;
                    }
                }


            String outputFile = request.getSession().getServletContext().getRealPath
                    ("/");
            outputFile = outputFile + "TMS表单" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xls";
            FileOutputStream fOut = new FileOutputStream(outputFile);

            workbook.write(fOut);
            fOut.flush();

            fOut.close();
            File file = new File(outputFile);

            String filename = file.getName();
            filename = URLEncoder.encode(filename, "UTF-8");

            InputStream fis = new BufferedInputStream(
                    new FileInputStream(outputFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(
                    response.getOutputStream());

            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            System.out.println("文件生成...");

        }catch (Exception e) {
//            list.add(false);
            System.out.println("生成失败 " + e);
        }
    }

    @RequestMapping("/selectTransportPlanByTid.do")
    @ResponseBody
    public String selectTransportPlanByTidByQuery(@RequestParam(value = "tid") int tid) throws Exception{
        TransportPlan transportPlan =  transportService.selectShipInfosByTidQuery(tid);
        for (int i=0;i<transportPlan.getShipInfoList().size();i++){
            String cname = FiledUtil.getAdd(transportPlan.getShipInfoList().get(i).getDeviceInfo().getLongitude(), transportPlan.getShipInfoList().get(i).getDeviceInfo().getLatitude());
            transportPlan.getShipInfoList().get(i).getDeviceInfo().setCname(cname);
        }
        return new ObjectMapper().writeValueAsString(transportPlan);
    }


    @RequestMapping("/selectShipAndDeviceByTid.do")
    @ResponseBody
    public void selectShipAndDeviceByTidByQuery(@RequestParam(value = "tid") int tid,HttpServletResponse response) throws Exception{
        TransportPlan transportPlan =  transportService.selectShipInfosByTidQuery(tid);
        for (int i=0;i<transportPlan.getShipInfoList().size();i++){
            String cname = FiledUtil.getAdd(transportPlan.getShipInfoList().get(i).getDeviceInfo().getLongitude(), transportPlan.getShipInfoList().get(i).getDeviceInfo().getLatitude());
            transportPlan.getShipInfoList().get(i).getDeviceInfo().setCname(cname);
        }
        List<ShipInfo> shipInfoList = new ArrayList<ShipInfo>();
        shipInfoList = transportPlan.getShipInfoList();
        //船舶名？？？问题
        response.setCharacterEncoding("utf-8");

        PrintWriter printWriter = response.getWriter();
        printWriter.print(StringUtil.toJson(shipInfoList));
        printWriter.flush();
        printWriter.close();
    }


    @RequestMapping("/updateTransportByStats.do")
    @ResponseBody
    public String updateTransportByStatsByQuery(@RequestParam(value = "tid") int tid,@RequestParam(value = "stats") int stats) throws Exception{
        transportService.updateTransportByStatsByQuery(tid,stats);
        return new ObjectMapper().writeValueAsString(true);
    }

    @RequestMapping("/selectGoodsTypePopulationCount.do")
    @ResponseBody
    public void selectGoodsTypePopulationCountByQuery(@RequestParam(value = "creationdate") String  creationdate,HttpServletResponse response) throws Exception{

        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        list = transportService.selectGoodsTypePopulationCount(new SimpleDateFormat("yyyy-MM-dd").parse(creationdate));

    }

    @RequestMapping("/selectTransportOrdernumber.do")
    @ResponseBody
    public String selectTransportOrdernumber(@RequestParam(value = "ordernumber") String ordernumber) throws Exception{
        int count = transportService.selectTransportOredernumber(ordernumber);
        if(count == 0){
            return new ObjectMapper().writeValueAsString(false);
        }else{
            return new ObjectMapper().writeValueAsString(true);
        }
    }

  @RequestMapping("/torecycleplan.do")
    public ModelAndView torecycleplan (HttpServletRequest request,@RequestParam(value = "pn",defaultValue="1") int pageNum) throws Exception{
      Map map = new HashMap();
      map.put("userid",users.getUserid(request));
      map.put("stats",1);
      PageHelper.startPage(pageNum,2);
      List<TransportPlan>  transportPlanList= transportService.selectByUseridToTransportQuery(map);
      PageInfo pageInfo = new PageInfo(transportPlanList);
      ModelAndView mav = new ModelAndView("/transport/recycleplan");
      if (transportPlanList != null){
          mav.addObject("pageInfo",pageInfo);
          mav.addObject("list",transportPlanList);
      }
      return mav;
  }
}
